package com.concurrent.coline.part1.create;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 *
 *类说明：如何新建线程
 */
public class NewThread {

    /**
     * 实现Runnable接口
     */
	private static class UseRun implements Runnable{

        @Override
		public void run() {
			System.out.println("I am implements Runnable");
		}
		
	}

    /**
     * 实现Callable接口，允许有返回值
     */
	private static class UseCall implements Callable<String>{

		@Override
		public String call() {
			System.out.println("I am implements Callable");
			return "CallResult";
		}
		
	}	
	
	public static void main(String[] args) 
			throws InterruptedException, ExecutionException {
        /*
            真实项目中启动线程最好使用线程池，
            否则有可能导致创建大量同类线程消耗完内存，
            也会增加线程间切换的成本（有可能切换时间比程序执行时间还要长）
         */
		UseRun useRun = new UseRun();
		new Thread(useRun).start();

		// Thread不支持Callable，所以借用FutureTask
		UseCall useCall = new UseCall();
		FutureTask<String> futureTask = new FutureTask<>(useCall);
		new Thread(futureTask).start();
		System.out.println(futureTask.get());
	}
}
